import { defineStore } from 'pinia'
import { authAPI } from '../api'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    user: JSON.parse(localStorage.getItem('user') || '{}')
  }),
  
  getters: {
    isLoggedIn: (state) => !!state.token,
    isAdmin: (state) => state.user.is_admin || false
  },
  
  actions: {
    // 登录
    async login(username, password) {
      const res = await authAPI.login(username, password)
      if (res.success) {
        this.token = res.token
        this.user = res.user
        localStorage.setItem('token', res.token)
        localStorage.setItem('user', JSON.stringify(res.user))
      }
      return res
    },
    
    // 注册
    async register(username, password) {
      return await authAPI.register(username, password)
    },
    
    // 登出
    logout() {
      this.token = ''
      this.user = {}
      localStorage.removeItem('token')
      localStorage.removeItem('user')
    },
    
    // 更新用户信息
    async fetchUser() {
      const res = await authAPI.getCurrentUser()
      if (res.success) {
        this.user = res.user
        localStorage.setItem('user', JSON.stringify(res.user))
      }
    }
  }
})

